<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.model.User"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%@page import="org.json.JSONObject"%>
<%@page import="org.json.JSONArray"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Vector"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
boolean nowy = (name==null || name.trim().equals("null"));
String id = name;
String action="update";
String save = "Zapisz";
String profil = "";
String def_tablespace = "";
String tmp_tablespace = "";
String role_data = "new Ext.data.SimpleStore({id:'name',	fields:[{name:'name'}],	data:[[]]})";
String sys_privs_data =  "new Ext.data.SimpleStore({id:'name',	fields:[{name:'name'}],	data:[[]]})";
boolean open = true;
User ob = null;
if(nowy){
	action="create";
	save = "Utwórz";
	name="Nowy użytkownik";
}else{
	ob = DbMetaData.getUser(u, name);
	profil = ob.getProfile();
	def_tablespace = ob.getDefaultTablespace();
	tmp_tablespace = ob.getTemporaryTablespace();
	open = ob.isOpen();
	Vector<String> v = ob.getRole();
	JSONArray data = new JSONArray();
	for (int i=0;i<v.size();i++) {
		String rola = v.get(i);
		List<String> properties = new ArrayList<String>();
		properties.add(rola);
		data.put(properties);
	}
	role_data = data.toString();
	
	v = ob.getSystemPrivs();
	data = new JSONArray();
	for (int i=0;i<v.size();i++) {
		String sp = v.get(i);
		List<String> properties = new ArrayList<String>();
		properties.add(sp);
		data.put(properties);
	}
	sys_privs_data = data.toString();
}
%>
<div class="container">
    <div id="<%=id%>-form"></div>
</div>
<script language="JavaScript">

Ext.apply(Ext.form.VTypes, {
	password : function(val, field) {
	if (field.initialPassField) {
	var login = Ext.getCmp(field.initialPassField);
	return (val == login.getValue());
	}
	return true;
	},
	passwordText : 'Wpisane hasła nie są zgodne'
});
role_store.load({
	params:{user:'<%=name%>'}
});//ladujemy role z bazy danych
sys_privs_store.load({
	params:{user:'<%=name%>'}
});//ladujemy przywileje z bazy danych
UserForm = Ext.extend(Ext.form.FormPanel, {
    renderTo: '<%=id%>-form',
    id: '<%=id%>-formid',
    iconCls: 'user-icon',
    frame: true,
    labelAlign: 'left',
    width: 850,
    url:'db/user.jsp',
    initComponent : function() {
   		 var config={
   		   	timeout:90,
        	defaultType: 'textfield',
        	defaults: {
            	anchor: '100%'
       		},
       		monitorValid:true,
       	    items: [
       	    {
       	    	xtype:'tabpanel',
           	    activeTab: 0,
           	    resizeTabs: true,
           	    animScroll:false,
       			minTabWidth: 135,
        		tabWidth: 135,
        		items:[
        			{
        			title:'Ogólne',
					layout:'form',
					frame:true,
					bodyStyle:'padding:10px',
					height:350,
					defaultType: 'textfield',
					defaults: {
						anchor: '95%'
					},
					items:[
       	    			{fieldLabel: 'Nazwa', name: 'name', allowBlank: false,value:'<%=name %>'<%=(nowy)?"":",readOnly:true"%>},
       	    			<%=(nowy)?"comboPROFILE({emptyText:'"+profil+"'})":"{fieldLabel:'Profil',name:'profile',allowBlank:false,value:'"+profil+"',readOnly:true}"%>,
		       	        {
		       	        	xtype:'fieldset',
		       	        	defaultType: 'textfield',
		       	        	title:'Uwierzytelnianie',
				        	defaults: {
				            	anchor: '95%'
				       		},
		       	        	items:[
		       	        		{fieldLabel:'Wpisz hasło',name:'pass',id:'<%=name+nowy%>pass',inputType:'password'},
		       	        		{fieldLabel:'Ponownie wpisz hasło',inputType:'password',vtype:'password',initialPassField:'<%=name+nowy%>pass'},
		       	        		{xtype:'checkbox',boxLabel:'Wygaś hasło',name:'expire'}
		       	        	]
		       	        },{
		       	        	xtype:'fieldset',
		       	        	defaultType: 'textfield',
		       	        	title:'Przestrzenie tabel',
				        	defaults: {
				            	anchor: '100%'
				       		},
		       	        	items:[
		       	        		comboTS({fieldLabel:'Domyślna',emptyText:'<%=def_tablespace%>'}),
		       	        		comboTS({name:'tmp_tablespace',fieldLabel:'Tymczasowa',emptyText:'<%=tmp_tablespace%>'})
		       	        	]
		       	        },{
		       	        	xtype:'radiogroup',
		       	        	fieldLabel:'Status',
				        	defaults: {
				            	anchor: '55%'
				       		},
		       	        	items:[
		       	        		{boxLabel:'Zablokowane',name:'lock',inputValue:'lock',checked:<%=(!open)%>},
		       	        		{boxLabel:'Odblokowane',name:'lock',inputValue:'unlock',checked:<%=(open)%>}
		       	        	]
		       	        }
		       	     ]//end ogolne items
        			},{		
							title:'Role',		
							layout:'fit',		
							height:350,		
							border:false,		
							autoScroll:true,
							frame:true,
							bodyStyle:'padding:10px',		
							items:[{
									xtype:'itemselector',
									name:'roles',
									imagePath: 'images/',
									drawUpIcon: false,				    
									drawDownIcon: false,
									drawTopIcon: false,
									drawBotIcon: false,	
									multiselects:[{
										width:450,
										height:150,
										store: role_store,
										displayField: 'name',
						                valueField: 'name'
									},{
										width:450,
										heigth:150,
										store:<%=role_data%>
									}]
								}
							]	
						},{		
							title:'Uprawnienia',		
							layout:'fit',		
							height:350,		
							border:false,		
							autoScroll:true,
							frame:true,
							bodyStyle:'padding:10px',		
							items:[	{
								xtype:'itemselector',
								name:'sys_privs',
								imagePath: 'images/',
								drawUpIcon: false,				    
								drawDownIcon: false,
								drawTopIcon: false,
								drawBotIcon: false,	
								multiselects:[{
									width:450,
									height:150,
									store: sys_privs_store
								},{
									width:450,
									heigth:150,
									store:<%=sys_privs_data%>
								}]
							}
							]	
						}       	       
        		 ]//end items tabpanel
       	    }//end tabpanel
       	    ],
       	    buttons:[
  	    	{
       	    	text: 'Zapisz',
       	    	iconCls: 'icon-save',
       	    	formBind:true,
       	    	scope: this,
       	    	handler:this.submit
           	},
           	{
           		text: 'Odśwież',
           		scope: this,
                handler: function(btn, ev){
                	this.getForm().load({url:'db/user.jsp',params:{name:'${name}',action:'get'},method:'POST'});
            	}
            }]
       };

   		Ext.apply(this, Ext.apply(this.initialConfig, config));
        UserForm.superclass.initComponent.apply(this, arguments);
    },
	onRender:function() {
	    UserForm.superclass.onRender.apply(this, arguments);
	    this.getForm().waitMsgTarget = this.getEl();
    },
	onLoadClick:function() {
    	this.load({
	    	url:this.url
	    	,waitMsg:'Ładowanie...'
	    	 ,params:{action:'get'},
	    	 failure:this.onFailure
    	});
    },
    submit:function() {
    	this.getForm().submit({
    		url:this.url,
    		scope:this,
    		success:this.onSuccess,
    		failure:this.onFailure,
    		params:{action:'<%=action%>'},
    		waitTitle:'proszę czekać.....',
    		waitMsg:'Trwa zapisywanie danych...'
    	});
   	},
   	onSuccess:function(form, action) {
   		obj = Ext.util.JSON.decode(action.response.responseText);
        var root = Ext.getCmp('sec-tree').getRootNode();
    	if( (catNode=root.findChild("t","289"))!=null){
    			catNode.reload();
    	}
   		<%if(nowy){%>
    	Ext.Msg.alert('DbExplorer','Z powodzeniem utworzono użytkownika');
				var w = Ext.getCmp('create-window');
				if(w){
					w.close();
				}
    	<%}%>
    },
    onFailure:function(form, action) {
    		this.showError(action.response.responseText);
    },
    showError:function(msg) {
    	obj = Ext.util.JSON.decode(msg);
    	 title = obj.error.title||'Error';
    	 Ext.Msg.show({
    		title:title,
    	 	msg:obj.error.msg||obj.error,
    	 	modal:true,
    	 	icon:Ext.Msg.ERROR,
    	 	buttons:Ext.Msg.OK
    	 });
    }
});
Ext.onReady(function() {
try{
	Ext.form.Field.prototype.msgTarget = 'side';
    var userForm = new UserForm({
    	renderTo: '<%=id%>-form'
    });
}catch(e){alert(e);}
});

</script>